using System;
using System.Collections.Generic;
using System.Text;
using WindowsLive.Writer.Api;
using System.Xml;
using System.Net;
using System.IO;
using System.Windows.Forms;

// Rhapsody 'Now Playing' Plugin for Windows Live Writer
// Created by: Justin Braun - http://www.justinbraun.com/
// Created: Wednesday, August 22, 2006
// Converted to C#: Monday, September 4, 2006

namespace RhapsodyNowPlayingPlugin
{

    [WriterPluginAttribute
       ("cc61a65b-3fb3-4776-b1ad-38dcd19af6d0",
           "Rhapsody 'Now Playing' Plugin",
            ImagePath = "Images.Rhapsody.png",
            HasEditableOptions = true,
            PublisherUrl = "http://www.justinbraun.com/",
            Description = "Embed currently playing song and artist from Rhapsody into your blog post")]


[InsertableContentSourceAttribute("Rhapsody Song")]
    public class RhapsodyNowPlayingPlugin : ContentSource 
    {
        public override DialogResult CreateContent(System.Windows.Forms.IWin32Window dialogOwner, ref string newContent)
        {
            waitForm waitSplash = null;

            try
            {
                //Splash Dialog
                waitSplash = new waitForm();
                waitSplash.Show();
                Application.DoEvents();

                // Download XML File
                newContent = GetContent(DownloadRhapsodyXml(Properties.Settings.Default.userXmlUrlString));
                
                // Close Splash Form
                waitSplash.Close();

                return DialogResult.OK;
            }
            catch (Exception ex)
            {
                waitSplash.Close();
                MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return DialogResult.OK;
            }
        }

        public override void EditOptions(System.Windows.Forms.IWin32Window dialogOwner)
        {
            // Show 'Options' form
            optionsForm myOptionsForm = new optionsForm();
            myOptionsForm.ShowDialog();
        }

        private string GetContent(XmlDocument xmlDoc)
        {
            //TODO: Add Exception Handling (Try/Catch) to this method

            // Different elements from XML document
            string artistName = xmlDoc.GetElementsByTagName("rhap:artist")[0].InnerText.ToString();
            string trackName = xmlDoc.GetElementsByTagName("rhap:track")[0].InnerText.ToString();
            string playLink = xmlDoc.GetElementsByTagName("rhap:play-href")[0].InnerText.ToString();
            string albumName = xmlDoc.GetElementsByTagName("rhap:album")[0].InnerText.ToString();

            // TODO: Get output text setting from configuration manager
            // Example: "I am listening to %l% by %a% on Rhapsody."
            // string output = ConfigurationSettings.AppSettings["outputTextFormat"].ToString();
            string output = Properties.Settings.Default.outputTextFormat;

            //Formatting for track hyperlink
            string trackLink = "<a href='" + playLink + "'>" + trackName + "</a>";

            // Replace parameters with settings from configuration manager
            output = output.Replace(@"%t%", trackLink);
            output = output.Replace(@"%a%", artistName);
            output = output.Replace(@"%b%", albumName);

            return "<p>" + output + "</p>";
        }
   
        public XmlDocument DownloadRhapsodyXml(string strURL)
        {
            WebClient myWebClient = null;
            StreamReader sr = null;
            XmlDocument xmlDoc;

            try
            {
                // Make web connection and download XML file
                myWebClient = new WebClient();
                Stream xmlData = myWebClient.OpenRead(strURL);
                sr = new StreamReader(xmlData);

                // Read Stream
                string xmlOutput = string.Empty;
                xmlOutput = sr.ReadToEnd();

                // Load Stream into XML Document
                xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xmlOutput);

                // Return XML Document
                return xmlDoc;
            }
            catch (Exception ex)
            {
                throw new Exception("Error: " + ex.Message.ToString());
            }
            finally
            {
                // Close web client
                myWebClient.Dispose();
                
                //Close streamreader if it is open
                if (sr == null)
                {
                    sr.Close();
                }
            }
        }

    }
}
